package com.ssyc.student.activity;

import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.TimerCountManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.student.R;
import com.ssyc.student.bean.ReadInfo;
import com.ssyc.student.fragment.StudentReadChooseAnswerFragment;
import com.ssyc.student.fragment.StudentReadCommitFragment;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--阅读界面
 * Created by Administrator on 2018/5/9 0009.
 */

public class StudentReadActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //返回图标
    private ImageView ivBack;

    //加载布局
    private RelativeLayout rlLoadingView;

    //内容布局
    private LinearLayout llContent;

    //计时器
    private Chronometer timer;

    //阅读文章的标题
    private TextView tvTitle;

    //阅读文章的内容
    private TextView tvContent;

    //显示ViewPager页面的文本
    private TextView tvVpPos;

    //ViewPager
    private SuperViewPager vp;

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;


    //填充ViewPager的Fragment集合
    private List<Fragment> mFragments;

    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录当前ViewPager滑动的位置
    private int pos = 0;

    //Handler对象
    private Handler handler = new Handler();

    //用于保存做题的选择题目答案的Map,key为当前的位置,value为选择的答案
    public static Map<Integer, String> chooseAnswerMap;

    //用于保存用户答题的对错的Map,key为当前的位置,value为答题的状态值
    public static Map<Integer, Boolean> answerMap;
    //整个模块对应的数据集合
    private ReadInfo.DataBean.QuestionListBean question_list;
    //所有问题对应的数据集合
    private List<ReadInfo.DataBean.QuestionListBean.DetailListBean> detail_list;


    //是否需要重新计时的标识
    public static boolean isNeedCountTime = true;

    //用于上传服务器记录时间的id
    private String rowId;


    //静态代码块
    {
        //这里使用有序的Map来存放题目
        chooseAnswerMap = new LinkedHashMap<>();
        answerMap = new LinkedHashMap<>();

        //初始化计时器
        TimeCount.init();
    }

    //获取保存答题Map的方法
    public static Map<Integer, String> getChooseAnswerMap() {
        return chooseAnswerMap;
    }

    //获取保存答题正确或者错误Map的方法
    public static Map<Integer, Boolean> getAnswerMap() {
        return answerMap;
    }

    //设置isNeedCountTime的方法
    public static void setIsNeedCountTime(boolean isNeedCountTime) {
        StudentReadActivity.isNeedCountTime = isNeedCountTime;
    }

    //提供给获取计时器控件的方法
    public Chronometer getTimer() {
        return timer;
    }

    public void setTimer(Chronometer timer) {
        this.timer = timer;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_read;
    }

    @Override
    protected void init() {
        showContent();

        //初始化控件
        initView();

        //获取Intent数据
        initIntent();

        //请求服务器数据
        http();
    }

    /**
     * 请求服务器数据的方法
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "22");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", "Lesson" + lessonId);
        map.put("examtype", "15");
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");
        map.put("role", AccountUtils.getRole(this));


        Log.i("test", "type=22&acc="+AccountUtils.getAccount(this)+"&lesson="+
                "Lesson" + lessonId+"&examtype=15&apptoken="+AccountUtils.getToken(this)+
        "&platform=8&role="+AccountUtils.getRole(this));
        HttpUtils.post(HttpAdress.READ, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoadingView) {
                    rlLoadingView.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("test", response);
                if (!TextUtils.isEmpty(response)) {
                    if (null != rlLoadingView) {
                        rlLoadingView.setVisibility(View.GONE);
                    }

                    ReadInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ReadInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            List<ReadInfo.DataBean> data = info.getData();
                            if (null != data && data.size() != 0) {
                                if (null != llContent) {
                                    llContent.setVisibility(View.VISIBLE);
                                }
                                ReadInfo.DataBean dataBean = data.get(0);
                                if (null != dataBean) {
                                    question_list = dataBean.getQuestion_list();
                                    if (null != question_list) {
                                        //设置大标题和文章内容
                                        setTopConent(question_list.getBig_title(), question_list.getQuestion());
                                        //获取题目的集合
                                        detail_list = question_list.getDetail_list();
                                        //初始化Fragment
                                        initFragments(detail_list);
                                        //初始化Vp
                                        initVp();
                                    }

                                }

                            } else {
                                //服务器返回异常状态码
                                UiUtils.Toast("服务器异常", false);
                                Log.i("test", "返回异常码是:" + info.getState());
                            }
                        }
                    }
                }
            }
        });

    }


    /**
     * 初始化View的控件
     */
    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        timer = findViewById(R.id.timer);
        tvVpPos = findViewById(R.id.tv_vp_pos);
        tvTitle = findViewById(R.id.tv__article_title);
        tvContent = findViewById(R.id.tv_article_content);
        vp = findViewById(R.id.vp);
        vp.addOnPageChangeListener(this);
        rlLoadingView = findViewById(R.id.rl_loading_view);
        llContent = findViewById(R.id.ll_content);
        rlLoadingView.setVisibility(View.VISIBLE);
        llContent.setVisibility(View.GONE);
        //启动计时器
        TimerCountManager.startTimer(true, timer);
    }


    /**
     * 设置标题和阅读的文章内容
     *
     * @param big_title
     * @param question
     */
    private void setTopConent(String big_title, String question) {
        if (!TextUtils.isEmpty(big_title)) {
            tvTitle.setText(big_title);
        }

        if (!TextUtils.isEmpty(question)) {
            tvContent.setText(question);
        }

    }


    /**
     * 获取传递过来的对象
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);
    }

    /**
     * 初始化Fragments的方法,需要在请求服务器后获取到数据后执行
     */
    private void initFragments(List<ReadInfo.DataBean.QuestionListBean.DetailListBean> beans) {
        if (null == beans || beans.size() == 0) {
            UiUtils.Toast("返回的问题为空", false);
            return;
        }

        mFragments = new ArrayList<>();

        for (int i = 0; i < beans.size(); i++) {
            mFragments.add(StudentReadChooseAnswerFragment.newInstance(beans.get(i), i));

            //保证每个选择的答案都有初始值
            chooseAnswerMap.put(i, "");

            //保证每个展示的答案对错的集合都有初始值
            answerMap.put(i, false);
        }

        //添加最后一个提交页面的Fragment
        mFragments.add(StudentReadCommitFragment.newInstance(lessonId, gradeId, question_list));

        //设置当前展示的Vp的页码
        tvVpPos.setText("1/" + (mFragments.size() - 1));

    }


    /**
     * 设置ViewPager的方法
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pos = position;
        if (position != mFragments.size() - 1) {
            tvVpPos.setVisibility(View.VISIBLE);
            tvVpPos.setText((position + 1) + "/" + (mFragments.size() - 1));
        } else {
            tvVpPos.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        //通知ViewPager翻页
        if (null != busInfo && StudentReadChooseAnswerFragment.VPSCOLL.equals(busInfo.vpScoll)) {
//            pos += 1;
            //延迟800毫秒跳转页面
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    vp.setCurrentItem(pos);
//                }
//            }, 300);
        } else if (null != busInfo && StudentShowReadAnswerActivity.ClOSE == busInfo.getType()) {
            //关闭当前页面
            finish();
        } else if (null != busInfo && StudentShowReadAnswerActivity.LOOKANSWER == busInfo.getType()) {
            //将当前VP切换到第一页
            vp.setCurrentItem(0);
        }
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        }
    }


    /**
     * 该生命周期内请求服务器记录初次进入的时间
     */
    @Override
    protected void onResume() {
        super.onResume();
        RecordTimeUtil.httpEnterTime(this, lessonId, gradeId, "15", new RecordTimeUtil.onRecordRowIdListener() {
            @Override
            public void recordRowId(String id, String en) {
                rowId = id;
            }
        });
    }


    /**
     * 考虑熄屏
     */
    @Override
    protected void onPause() {
        super.onPause();

        TimerCountManager.stopTimer(timer);

        long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

        //计算总用时
        long totalTime = TimeCount.newInstance().getTotalTime() + time;

        //记录总用时
        TimeCount.newInstance().setTotalTime(totalTime);

        //上传服务器记录时间的接口
        RecordTimeUtil.httpExitTime(rowId, this);
    }

    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();

        if (isNeedCountTime) {
            TimerCountManager.startTimer(false, timer);
        }

        //重置LastTime
        TimeCount.newInstance().setLastTime(System.currentTimeMillis());
    }

    /**
     * 生命周期中停止计时
     */
    @Override
    protected void onDestroy() {
        //销毁时停止计时
        TimerCountManager.stopTimer(timer);

        //取消Handler的任务
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        //还原计时器的时间统计
        TimeCount.newInstance().setTotalTime(0);
        TimeCount.newInstance().setLastTime(0);

        //还原状态
        setIsNeedCountTime(true);

        super.onDestroy();
    }


}
